package com.leisurexi.aop.features.advisor;

import com.leisurexi.aop.overview.EchoService;
import org.springframework.aop.IntroductionInfo;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultIntroductionAdvisor;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author: leisurexi
 * @date: 2021-06-05 15:51
 */
public class IntroductionAdvisorDemo implements EchoService, Comparable<IntroductionAdvisorDemo> {

    public static void main(String[] args) {
        IntroductionAdvisorDemo target = new IntroductionAdvisorDemo();
        // 使用此构造函数会使 IntroductionInfo 无效
//        ProxyFactory proxyFactory = new ProxyFactory(target);

        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setTarget(target);

        // 添加 IntroductionAdvisor
        proxyFactory.addAdvisor(new DefaultIntroductionAdvisor(new MethodBeforeAdvice() {
            @Override
            public void before(Method method, Object[] args, Object target) throws Throwable {
                System.out.println("BeforeAdvice: " + method);
            }
        }, new IntroductionInfo() {
            @Override
            public Class<?>[] getInterfaces() {
                return new Class[]{EchoService.class, Map.class};
            }
        }));

        EchoService echoService = (EchoService) proxyFactory.getProxy();
        echoService.echo("leisurexi");

        // 因为未实现 Map 接口所以会抛出异常，但是还是可以正常拦截的
        Map map = (Map) proxyFactory.getProxy();
        map.put("leisurexi", 1);

        Comparable comparable = (Comparable) proxyFactory.getProxy();
        comparable.compareTo(null);
    }

    @Override
    public int compareTo(IntroductionAdvisorDemo o) {
        return 0;
    }

    @Override
    public String echo(String message) throws NullPointerException {
        return "IntroductionAdvisorDemo : " + message;
    }

}
